package org.swqsbssddqs.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.swqsbssddqs.shortlink.admin.common.convention.exception.ClientException;
import org.swqsbssddqs.shortlink.admin.dao.entity.UserDO;
import org.swqsbssddqs.shortlink.admin.dao.mapper.UserMapper;
import org.swqsbssddqs.shortlink.admin.dto.req.UserLoginReqDTO;
import org.swqsbssddqs.shortlink.admin.dto.req.UserRegisterReqDTO;
import org.swqsbssddqs.shortlink.admin.dto.req.UserUpdateReqDTO;
import org.swqsbssddqs.shortlink.admin.dto.resp.UserLoginRespDTO;
import org.swqsbssddqs.shortlink.admin.dto.resp.UserRespDTO;
import org.swqsbssddqs.shortlink.admin.service.GroupService;
import org.swqsbssddqs.shortlink.admin.service.UserService;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static org.swqsbssddqs.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static org.swqsbssddqs.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static org.swqsbssddqs.shortlink.admin.common.enums.UserErrorCodeEnum.*;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
    private final RBloomFilter<String> userRegisterBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;
    @Override
    public UserRespDTO getUserByUsername(String username) {
        QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        UserDO userDO = baseMapper.selectOne(wrapper);
        UserRespDTO userRespDTO = new UserRespDTO();
        BeanUtils.copyProperties(userDO,userRespDTO);
        return userRespDTO;
    }

    @Override
    public Boolean hasUsername(String username) {
        return userRegisterBloomFilter.contains(username);
    }

    @Override
    @Transactional
    public void register(UserRegisterReqDTO requestParam) {
        if(hasUsername(requestParam.getUsername())){
            throw new ClientException(USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        if(!lock.tryLock()){
            throw new ClientException(USER_NAME_EXIST);
        }
        try{
            try{
               baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
            }catch (DuplicateKeyException e){
                throw new ClientException(USER_EXIST);
            }catch (Exception e){
                throw new ClientException(USER_SAVE_ERROR);
            }
            userRegisterBloomFilter.add(requestParam.getUsername());
            groupService.create(requestParam.getUsername(),"默认分组");
        }finally {
            lock.unlock();
        }


    }

    @Override
    public void update(UserUpdateReqDTO userUpdateReqDTO) {
        //TODO 验证当前登录用户是否和修改的用户名相同

        LambdaUpdateWrapper<UserDO> eq = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, userUpdateReqDTO.getUsername());
        baseMapper.update(BeanUtil.copyProperties(userUpdateReqDTO,UserDO.class),eq);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        LambdaQueryWrapper<UserDO> eq = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, userLoginReqDTO.getUsername())
                .eq(UserDO::getPassword, userLoginReqDTO.getPassword())
                .eq(UserDO::getDelFlag, 0);

        UserDO userDO = baseMapper.selectOne(eq);
        if(userDO==null){
            throw new ClientException("用户不存在");
        }

        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY + userLoginReqDTO.getUsername());
        //防止重复登陆
        if(CollUtil.isNotEmpty(entries)){
            stringRedisTemplate.expire(USER_LOGIN_KEY + userLoginReqDTO.getUsername(),30, TimeUnit.DAYS);
            String token = entries.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put(USER_LOGIN_KEY + userLoginReqDTO.getUsername(),uuid, JSON.toJSONString(userDO));
        stringRedisTemplate.expire(USER_LOGIN_KEY + userLoginReqDTO.getUsername(),30, TimeUnit.DAYS);
        return new UserLoginRespDTO(uuid);
    }
    public Boolean checkLogin(String username,String token){
        return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username,token)!=null;
    }

    @Override
    public void logout(String username, String token) {
        if(!checkLogin(username,token)){
            throw new ClientException("用户未登录");
        }
        stringRedisTemplate.delete(USER_LOGIN_KEY + username);
    }
}
